package com.gientech.framework.common.utils;

import com.gientech.framework.common.query.Query;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

/**
 * @author gang.tu
 * @ClassName PageUtil
 * @Description
 * @Date 2022/10/18 19:41
 */
@Data
public class PageUtil {
    /**
     * @description 开始页面冲1开始
     * @author gang.tu
     * @date 2022/10/18 19:45
     */
    public static <T extends Query> T checkAnddealPage(T t) {
        Integer currentPage = t.getCurrentPage();
        Integer pageSize = t.getPageSize();
        if (currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 1;
        }
        t.setCurrentPage(currentPage - 1);
        t.setPageSize(pageSize);
        return t;
    }

    /**
     * @description
     * @author gang.tu
     * @date 2022/11/7 11:24
     * @return: org.springframework.data.domain.PageRequest
     */
    public static PageRequest getPageable(Query query) {
        query = checkAnddealPage(query);
        return PageRequest.of(query.getCurrentPage(), query.getPageSize());
    }

    /**
     * @description 分页添加排序
     * @author gang.tu
     * @date 2022/12/13 11:15
     * @return: org.springframework.data.domain.PageRequest
     */
    public static PageRequest getPageable(Query query, Sort sort) {
        query = checkAnddealPage(query);
        return PageRequest.of(query.getCurrentPage(), query.getPageSize(), sort);
    }
}